package com.sqx.modules.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.dao.*;
import com.sqx.modules.course.entity.*;
import com.sqx.modules.course.entity.vo.SelCourseByClassifyVo;
import com.sqx.modules.course.service.CourseService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.search.service.AppSearchService;
import com.sqx.modules.utils.HttpClientUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseDao, Course> implements CourseService {
    @Autowired
    private CourseDetailsDao courseDetailsDao;
    @Autowired
    private CourseCollectDao courseCollectDao;
    @Autowired
    private CourseUserDao courseUserDao;
    @Autowired
    private AppSearchService appSearchService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private AdsUnlockVideosDao adsUnlockVideosDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CourseClassificationDao courseClassificationDao;
    @Autowired
    private CoursePursueDao coursePursueDao;



    /**
     * 创建线程池处理业务逻辑
     */
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(30, 100,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());


    private static boolean sys=false;

    @Override
    public Result insertCourse(Course course) {
        //设置删除标识
        course.setIsDelete(0);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置创建时间
        course.setCreateTime(df.format(new Date()));
        //设置更新时间
        course.setUpdateTime(df.format(new Date()));
        if(course.getCourseType().equals(2) || course.getCourseType().equals(3)){
            baseMapper.insert(course);
            CourseDetails courseDetails=new CourseDetails();
            courseDetails.setCourseId(course.getCourseId());
            courseDetails.setVideoUrl(course.getRemark());
            courseDetailsDao.insert(courseDetails);
        }else{
            baseMapper.insert(course);
        }
        return Result.success("操作成功！");
    }

    @Override
    public Result updateCourse(Course course) {
        baseMapper.updateById(course);
        return Result.success("操作成功！");
    }

    @Override
    public Result updateDelete(Long id) {
        baseMapper.updateDelete(id);
        return Result.success("操作成功！");
    }

    @Override
    public Result selectCourse(Integer page, Integer limit, Long classifyId, String title,Integer isRecommend,Integer status,
                               Long bannerId,Integer sort,String token, Integer isPrice,Integer selType) {
        Long userId=null;
        if(StringUtils.isNotEmpty(token)){
            Claims claims = jwtUtils.getClaimByToken(token);
            if(claims != null && !jwtUtils.isTokenExpired(claims.getExpiration())){
                userId=Long.parseLong(claims.getSubject());
            }
        }
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        // 一周第一天为周日，所以此处日+1
        calendar.setWeekDate(calendar.getWeekYear(), calendar.get(Calendar.WEEK_OF_YEAR), 2);
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                0, 0, 0);
        String startTime=sdf.format(calendar.getTime());
        // 一周第一天为周日，所以此处为下一周第一天
        calendar.setWeekDate(calendar.getWeekYear(), calendar.get(Calendar.WEEK_OF_YEAR)+1, 1);
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                23, 59, 59);
        String endTime=sdf.format(calendar.getTime());

        if (ObjectUtils.isNotEmpty(selType)){
            LambdaQueryWrapper<CourseClassification> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CourseClassification::getIsDelete, 0);
            List<CourseClassification> courseClassifications = courseClassificationDao.selectList(lambdaQueryWrapper);
            HashMap<Long, String> hashMap = new HashMap<>();
            if (ObjectUtils.isNotEmpty(courseClassifications)){
                for (CourseClassification courseClassification : courseClassifications) {
                    hashMap.put(courseClassification.getClassificationId(),courseClassification.getClassificationName());
                }
            }
            Page<Course> objectPage = new Page<>(ObjectUtils.isEmpty(page) ? 1 : page, ObjectUtils.isEmpty(limit) ? 10 : limit);
            if (selType==1){//精选(购买次数)
                LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
                courseLambdaQueryWrapper.eq(Course::getStatus, 1);
                courseLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(classifyId),Course::getClassifyId,classifyId);
                courseLambdaQueryWrapper.orderByDesc(Course::getPayNum);
                courseLambdaQueryWrapper.eq(Course::getIsDelete,0);
                IPage<Course> iPage = baseMapper.selectPage(objectPage, courseLambdaQueryWrapper);
                for (Course record : iPage.getRecords()) {
                    LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId, record.getCourseId());
                    courseDetailsLambdaQueryWrapper.orderByAsc(CourseDetails::getSort);
                    List<CourseDetails> details = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
                    courseDetailsLambdaQueryWrapper.last("limit 1");
                    CourseDetails courseDetails = courseDetailsDao.selectOne(courseDetailsLambdaQueryWrapper);
                    if(ObjectUtils.isNotEmpty(courseDetails)){
                        record.setCourseDetailsName(courseDetails.getCourseDetailsName());
                        record.setCourseDetailsId(courseDetails.getCourseDetailsId());
                        record.setClassificationName(hashMap.get(record.getClassifyId()));
                        record.setCourseDetailsCount(details.size());
                    }
                }
                return Result.success().put("data", new PageUtils(iPage));
            } else if (selType == 2) {//热门(播放量)
                LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
                courseLambdaQueryWrapper.eq(Course::getStatus, 1);
                courseLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(classifyId),Course::getClassifyId,classifyId);
                courseLambdaQueryWrapper.orderByDesc(Course::getViewCounts);
                courseLambdaQueryWrapper.eq(Course::getIsDelete,0);
                IPage<Course> iPage = baseMapper.selectPage(objectPage, courseLambdaQueryWrapper);
                for (Course record : iPage.getRecords()) {
                    LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId, record.getCourseId());
                    courseDetailsLambdaQueryWrapper.orderByAsc(CourseDetails::getSort);
                    List<CourseDetails> details = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
                    courseDetailsLambdaQueryWrapper.last("limit 1");
                    CourseDetails courseDetails = courseDetailsDao.selectOne(courseDetailsLambdaQueryWrapper);
                    record.setCourseDetailsName(courseDetails.getCourseDetailsName());
                    record.setCourseDetailsId(courseDetails.getCourseDetailsId());
                    record.setClassificationName(hashMap.get(record.getClassifyId()));
                    record.setCourseDetailsCount(details.size());
                }
                return Result.success().put("data", new PageUtils(iPage));
            } else if (selType == 3) {//最新（最近更新）
                LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
                courseLambdaQueryWrapper.eq(Course::getStatus, 1);
                courseLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(classifyId),Course::getClassifyId,classifyId);
                courseLambdaQueryWrapper.orderByDesc(Course::getCreateTime);
                courseLambdaQueryWrapper.eq(Course::getIsDelete,0);
                IPage<Course> iPage = baseMapper.selectPage(objectPage, courseLambdaQueryWrapper);
                for (Course record : iPage.getRecords()) {
                    LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId, record.getCourseId());
                    courseDetailsLambdaQueryWrapper.orderByAsc(CourseDetails::getSort);
                    List<CourseDetails> details = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
                    courseDetailsLambdaQueryWrapper.last("limit 1");
                    CourseDetails courseDetails = courseDetailsDao.selectOne(courseDetailsLambdaQueryWrapper);
                    record.setCourseDetailsName(courseDetails.getCourseDetailsName());
                    record.setCourseDetailsId(courseDetails.getCourseDetailsId());
                    record.setClassificationName(hashMap.get(record.getClassifyId()));
                    record.setCourseDetailsCount(details.size());
                }
                return Result.success().put("data", new PageUtils(iPage));
            }
        }
        //sort为null按时间排序sort=2按播放量排序，sort=1按点赞量排序
        //goodNum查询整部剧的点赞数
        //courseDetailsName：查询的是最后一条历史记录的剧集名称
        //courseDetailsId：查询用户最后一条历史记录的剧集id
        //weekGoodNum：短剧1周的点赞
        //主查询根据不同的条件查到course不同的数据，根据金刚区分类查，根据短剧标题查，根据bannerId查，是否推荐，根据周点赞排序
        return Result.success().put("data", new PageUtils(baseMapper.selectCourse(pages, classifyId, title,isRecommend,status,bannerId,
                sort,startTime,endTime,userId,isPrice,selType)));
    }

    /*@Override
    public Result selectCourseById(Long id, Long userId) {
        //查询短剧信息
        Course bean = baseMapper.selectById(id);
        if (userId != null) {
            bean.setIsCollect(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>().eq("user_id", userId).eq("course_id", id)));
        } else {
            bean.setIsCollect(0);
        }
        //查询用户是否购买了这本书
        CourseUser courseUser = courseUserDao.selectCourseUser(id, userId);
        Orders one = ordersService.selectOrdersByCourseIdAndUserId(userId,id);
        if (courseUser != null) {
            bean.setListsDetail(courseDetailsDao.findByCourseId(id));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            courseUser.setUpdateTime(df.format(new Date()));
            courseUserDao.updateCourseTime(courseUser);
            bean.setIsMyCourse(2);
            bean.setOrders(one);
        }else{
            if(bean.getCourseType()==null || bean.getCourseType().equals(1)){
                bean.setListsDetail(courseDetailsDao.findByCourseIdNotUrl(id));
            }
            bean.setIsMyCourse(1);
        }
        return Result.success().put("data", bean);
    }*/

    @Override
    public Result selectCourseById(Integer page,Integer limit,Long id,Integer good) {
        Page<CourseDetails> pages=new Page<>(page,limit);
        return Result.success().put("data", new PageUtils(courseDetailsDao.selectCoursePageByCourseId(pages,id,good)));
    }

    @Override
    public Result selectCourseTitle(Integer page, Integer limit, String title, Long userId) {
        //分页
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        if(userId!=null){
            //记录或更新搜索内容
            appSearchService.insetAppSearch(title, userId);
        }
        //拼接模糊查询
        String title1 = null;
        if (StringUtils.isNotBlank(title)) {
            title1 = "%" + title + "%";
            return Result.success().put("data", new PageUtils(baseMapper.selectCourseTitle(pages, title1)));
        } else {
            return Result.error("请输入要搜索的内容！");
        }

    }

    @Override
    public Result synCourse(){
        if(sys){
            return Result.error("视频正在同步中，请稍等！");
        }
        sys=true;
        singleThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String value = commonInfoService.findOne(250).getValue();
                    String s = HttpClientUtil.doGet(value);
                    log.error("返回值："+s);
                    JSONArray jsonArray = JSONArray.parseArray(s);
                    for (int i=2;i<jsonArray.size();i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String cname = jsonObject.getString("cname");
                        String name = jsonObject.getString("name");
                        String m3u8url = jsonObject.getString("m3u8url");
                        String picurl = jsonObject.getString("picurl");
                        String description = jsonObject.getString("description");
                        Course course = baseMapper.selectOne(new QueryWrapper<Course>().eq("title", cname));
                        if(course==null){
                            course=new Course();
                            course.setTitle(cname);
                            course.setTitleImg(picurl);
                            course.setPrice(BigDecimal.ZERO);
                            course.setPayNum(0);
                            course.setImg(picurl);
                            course.setDetails(description);
                            course.setIsDelete(0);
                            course.setCreateTime(DateUtils.format(new Date()));
                            course.setUpdateTime(course.getCreateTime());
                            course.setIsRecommend(0);
                            course.setStatus(2);
                            course.setIsPrice(2);
                            course.setViewCounts(0);
                            baseMapper.insert(course);
                        }else{
                            course.setTitle(cname);
                            course.setTitleImg(picurl);
                            course.setImg(picurl);
                            course.setDetails(description);
                            baseMapper.updateById(course);
                        }
                        Integer count = courseDetailsDao.selectCount(new QueryWrapper<CourseDetails>().eq("course_details_name", name));
                        if(count==0){
                            CourseDetails courseDetails=new CourseDetails();
                            courseDetails.setCourseId(course.getCourseId());
                            courseDetails.setCourseDetailsName(name);
                            courseDetails.setVideoUrl(m3u8url);
                            courseDetails.setCreateTime(DateUtils.format(new Date()));
                            courseDetails.setTitleImg(picurl);
                            courseDetails.setContent(description);
                            courseDetails.setGoodNum(0);
                            courseDetails.setPrice(BigDecimal.ZERO);
                            courseDetails.setIsPrice(2);
                            courseDetailsDao.insert(courseDetails);
                        }else{
                            CourseDetails courseDetails = courseDetailsDao.selectOne(new QueryWrapper<CourseDetails>().eq("course_details_name", name).last(" limit 1"));
                            courseDetails.setCourseDetailsName(name);
                            courseDetails.setVideoUrl(m3u8url);
                            courseDetails.setCreateTime(DateUtils.format(new Date()));
                            courseDetails.setTitleImg(picurl);
                            courseDetails.setContent(description);
                            courseDetailsDao.updateById(courseDetails);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("同步视频出错："+e.getMessage(),e);
                }finally {
                    sys=false;
                }
            }
        });
        return Result.success();
    }

    @Override
    public Result updateCourseDetails(String ids,BigDecimal price,String content,String titleImg){
        for (String id:ids.split(",")){
            CourseDetails courseDetails = courseDetailsDao.selectById(Long.parseLong(id));
            courseDetails.setPrice(price);
            if(price.doubleValue()==0){
                courseDetails.setIsPrice(2);
            }else{
                courseDetails.setIsPrice(1);
            }
            courseDetails.setContent(content);
            courseDetails.setTitleImg(titleImg);
            courseDetailsDao.updateById(courseDetails);
        }
        return Result.success();
    }

    @Override
    public Result updateCourseStatus(String ids, Integer status){
        for (String id:ids.split(",")){
            Course course = baseMapper.selectById(Long.parseLong(id));
            course.setStatus(status);
            baseMapper.updateById(course);
        }
        return Result.success();
    }



    @Override
    public Result deleteCourseByIds(String ids){
        for (String id:ids.split(",")){
            baseMapper.deleteById(Long.parseLong(id));
            courseDetailsDao.delete(new QueryWrapper<CourseDetails>().eq("course_id",Long.parseLong(id)));
        }
        return Result.success();
    }

    @Override
    public Result deleteCourseDetailsByIds(String ids){
        for (String id:ids.split(",")){
            courseDetailsDao.deleteById(Long.parseLong(id));
        }
        return Result.success();
    }

    /**
     * 分页查询首页推荐剧集
     * @param userId 用户id
     * @param page 页数
     * @param limit 每页条数
     * @param title 标题
     * @return 首页推荐剧集
     */
    @Override
    public Result selectHomePage(Long userId, Integer page,Integer limit, String title) {
        //查询CourseDetails中所有推荐的短剧,随机排序
        IPage<CourseDetails> courseDetailsIPage = courseDetailsDao.selectCourseDetailsList(new Page<>(ObjectUtils.isEmpty(page)?1:page, ObjectUtils.isEmpty(limit)?5:limit));
        if (userId != null) {
            List<CourseDetails> records = courseDetailsIPage.getRecords();
            for (CourseDetails courseDetails : records){
                //判断付费剧集是否已经解锁
                if (courseDetails.getIsPrice() == 1) {
                    //是否购买整剧
                    LambdaQueryWrapper<CourseUser> courseUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    courseUserLambdaQueryWrapper.eq(CourseUser::getUserId, userId);
                    courseUserLambdaQueryWrapper.eq(CourseUser::getCourseId, courseDetails.getCourseId());
                    courseUserLambdaQueryWrapper.eq(CourseUser::getClassify,1);
                    CourseUser user = courseUserDao.selectOne(courseUserLambdaQueryWrapper);
                    if (ObjectUtils.isEmpty(user))courseDetails.setIsUnlockVideos(2);
                    //是否购买单集
                    LambdaQueryWrapper<CourseUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    userLambdaQueryWrapper.eq(CourseUser::getUserId, userId);
                    userLambdaQueryWrapper.eq(CourseUser::getCourseDetailsId, courseDetails.getCourseDetailsId());
                    userLambdaQueryWrapper.eq(CourseUser::getClassify,2);
                    CourseUser selectOne = courseUserDao.selectOne(userLambdaQueryWrapper);
                    if (ObjectUtils.isEmpty(selectOne))courseDetails.setIsUnlockVideos(2);
                    //是否广告解锁
                    LambdaQueryWrapper<AdsUnlockVideos> adsUnlockVideosLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    adsUnlockVideosLambdaQueryWrapper.eq(AdsUnlockVideos::getUserId, userId);
                    adsUnlockVideosLambdaQueryWrapper.eq(AdsUnlockVideos::getCourseDetailsId, courseDetails.getCourseDetailsId());
                    adsUnlockVideosLambdaQueryWrapper.eq(AdsUnlockVideos::getWatchStatus,1);
                    adsUnlockVideosLambdaQueryWrapper.eq(AdsUnlockVideos::getUnlockStatus,1);
                    if (ObjectUtils.isEmpty(adsUnlockVideosDao.selectOne(adsUnlockVideosLambdaQueryWrapper)))courseDetails.setIsUnlockVideos(2);
                }
                //判断是否收藏
                LambdaUpdateWrapper<CourseCollect> courseCollectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                courseCollectLambdaUpdateWrapper.eq(CourseCollect::getUserId, userId);
                courseCollectLambdaUpdateWrapper.eq(CourseCollect::getCourseDetailsId, courseDetails.getCourseDetailsId());
                courseCollectLambdaUpdateWrapper.eq(CourseCollect::getClassify,1);
                //判断是否点赞
                LambdaUpdateWrapper<CourseCollect> collectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                collectLambdaUpdateWrapper.eq(CourseCollect::getUserId, userId);
                collectLambdaUpdateWrapper.eq(CourseCollect::getCourseDetailsId, courseDetails.getCourseDetailsId());
                collectLambdaUpdateWrapper.eq(CourseCollect::getClassify,2);

                courseDetails.setIsCollect(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId).eq("course_details_id", courseDetails.getCourseDetailsId()).eq("classify",1)));
                courseDetails.setIsGood(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId).eq("course_details_id", courseDetails.getCourseDetailsId()).eq("classify",2)));
                courseDetails.setCourse(courseDao.selectById(courseDetails.getCourseId()));
                courseDetails.setTitle(courseDetails.getCourse().getTitle());
                courseDetails.setCourseDetailsCount(courseDetailsDao.selectCount(new QueryWrapper<CourseDetails>().eq("course_id",courseDetails.getCourseId())));
            }
        }
        return Result.success().put("data",courseDetailsIPage);
    }

    @Override
    public Result selIsCollect(Long courseId, Long userId) {
        LambdaQueryWrapper<CourseCollect> courseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseCollectLambdaQueryWrapper.eq(CourseCollect::getUserId,userId);
        courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseId,courseId);
        List<CourseCollect> courseCollects = courseCollectDao.selectList(courseCollectLambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(courseCollects)){
            for (CourseCollect courseCollect : courseCollects) {
                if (courseCollect.getClassify()==1){
                    return Result.success().put("data",true);
                }
            }
            return Result.success().put("data",false);
        }else {
            return Result.success().put("data",false);
        }
    }

    @Override
    public Result selectRecommendCourseDetailsList(Long userId, Integer page, Integer limit) {
        Page<CourseDetails> courseDetailsPage = new Page<>(ObjectUtils.isEmpty(page)?1:page,ObjectUtils.isEmpty(limit)?10:limit);
        return Result.success().put("data",courseDao.selectRecommendCourseDetailsList(courseDetailsPage,userId));
    }

    //查询该剧下面是否有剧集被收藏（历史记录？），收藏则表示在追剧，没有则表示未追剧
    @Override
    public Result selCourseByCourseCollect(Long userId,Integer courseId,int classify) {
        LambdaQueryWrapper<CourseCollect> courseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseCollectLambdaQueryWrapper.eq(CourseCollect::getUserId,userId);
        courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseId,courseId);
        courseCollectLambdaQueryWrapper.eq(CourseCollect::getClassify,classify);
        List<CourseCollect> courseCollects = courseCollectDao.selectList(courseCollectLambdaQueryWrapper);
        Boolean bool = false;
        HashMap<String, Boolean> map = new HashMap<>();
        if(ObjectUtils.isNotEmpty(courseCollects)){
           map.put("bool",true);
        }else {
            map.put("bool",false);
        }
        return Result.success().put("data",map);
    }

    @Override
    public Result selectHomePageCourse(Integer page, Integer limit, String title,String userId) {
        List<CourseClassification> courseClassifications = courseClassificationDao.selectList(null);
        if(ObjectUtils.isNotEmpty(courseClassifications)){
            List<SelCourseByClassifyVo> selCourseByClassifyVos = new ArrayList<>();
            for (CourseClassification courseClassification : courseClassifications) {
                SelCourseByClassifyVo selCourseByClassifyVo = new SelCourseByClassifyVo();
                selCourseByClassifyVo.setClassifyId(courseClassification.getClassificationId().intValue());
                selCourseByClassifyVo.setClassifyName(courseClassification.getClassificationName());
                LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
                courseLambdaQueryWrapper.eq(Course::getClassifyId,courseClassification.getClassificationId());
                courseLambdaQueryWrapper.eq(Course::getIsDelete,0);
                List<Course> courses = courseDao.selectList(courseLambdaQueryWrapper);
                for (Course course : courses) {
                    LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId,course.getCourseId());
                    courseDetailsLambdaQueryWrapper.orderByAsc(CourseDetails::getSort);
//                    courseDetailsLambdaQueryWrapper.last("LIMIT 1");
                    List<CourseDetails> courseDetails = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
                    if(ObjectUtils.isNotEmpty(courseDetails)){
                        course.setCourseDetailsCount(courseDetails.size());
                        course.setCourseDetailsId(courseDetails.get(0).getCourseDetailsId());
                        course.setCourseDetailsName(courseDetails.get(0).getCourseDetailsName());
                    }
                    if(ObjectUtils.isNotEmpty(userId)){
//                        LambdaQueryWrapper<CourseCollect> courseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                        courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseId,course.getCourseId());
//                        courseCollectLambdaQueryWrapper.eq(CourseCollect::getUserId,userId);
//                        List<CourseCollect> courseCollects = courseCollectDao.selectList(courseCollectLambdaQueryWrapper);
//                        course.setIsCollect(ObjectUtils.isNotEmpty(courseCollects)?1:0);
                        LambdaQueryWrapper<CoursePursue> coursePursueLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        coursePursueLambdaQueryWrapper.eq(CoursePursue::getCourseId,course.getCourseId());
                        coursePursueLambdaQueryWrapper.eq(CoursePursue::getUserId,userId);
                        List<CoursePursue> coursePursues = coursePursueDao.selectList(coursePursueLambdaQueryWrapper);
                        //是否追剧
                        course.setIsCollect(ObjectUtils.isNotEmpty(coursePursues)?1:0);
                    }
                }
                selCourseByClassifyVo.setCourses(courses);
                selCourseByClassifyVos.add(selCourseByClassifyVo);
            }
            return Result.success().put("data",selCourseByClassifyVos);
        }
        return Result.success().put("data",new ArrayList<SelCourseByClassifyVo>());
    }

    @Override
    public Result addCoursePursue(Long userId, Integer courseId) {
        LambdaQueryWrapper<CoursePursue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CoursePursue::getUserId,userId);
        lambdaQueryWrapper.eq(CoursePursue::getCourseId,courseId);
        CoursePursue coursePursue = coursePursueDao.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(coursePursue)){
            coursePursueDao.deleteById(coursePursue.getId());
        }else {
            CoursePursue pursue = new CoursePursue();
            pursue.setUserId(userId.intValue());
            pursue.setCourseId(courseId);
            pursue.setCreateTime(new Date());
            coursePursueDao.insert(pursue);
        }
        return Result.success();
    }

    @Override
    public Result coursePursueByUserId(Long userId,Integer page,Integer limit) {
        LambdaQueryWrapper<CoursePursue> coursePursueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        coursePursueLambdaQueryWrapper.eq(CoursePursue::getUserId,userId);
        List<CoursePursue> coursePursues = coursePursueDao.selectList(coursePursueLambdaQueryWrapper);
        LambdaQueryWrapper<CourseClassification> courseClassificationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseClassificationLambdaQueryWrapper.eq(CourseClassification::getIsDelete, 0);
        List<CourseClassification> courseClassifications = courseClassificationDao.selectList(courseClassificationLambdaQueryWrapper);
        HashMap<Long, String> hashMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(courseClassifications)){
            for (CourseClassification courseClassification : courseClassifications) {
                hashMap.put(courseClassification.getClassificationId(),courseClassification.getClassificationName());
            }
        }
        if (ObjectUtils.isNotEmpty(coursePursues)){
            List<Integer> collect = coursePursues.stream().map(CoursePursue::getCourseId).collect(Collectors.toList());
            LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            courseLambdaQueryWrapper.in(Course::getCourseId,collect);
            courseLambdaQueryWrapper.eq(Course::getIsDelete,0);
            courseLambdaQueryWrapper.orderByDesc(Course::getCreateTime);
            Page<Course> coursePage = new Page<>(page,limit);
            IPage<Course> courseIPage = courseDao.selectPage(coursePage,courseLambdaQueryWrapper);
            for (Course record : courseIPage.getRecords()) {
                record.setClassificationName(hashMap.get(record.getClassifyId()));
                LambdaQueryWrapper<CourseDetails> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CourseDetails::getCourseId,record.getCourseId());
                wrapper.orderByAsc(CourseDetails::getCreateTime);
                List<CourseDetails> courseDetails = courseDetailsDao.selectList(wrapper);
                record.setCourseDetailsId(courseDetails.get(0).getCourseDetailsId());
                record.setCourseDetailsName(courseDetails.get(0).getCourseDetailsName());
                record.setCourseDetailsCount(courseDetails.size());
                LambdaQueryWrapper<CoursePursue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CoursePursue::getUserId,userId);
                lambdaQueryWrapper.eq(CoursePursue::getCourseId,record.getCourseId());
                Integer count = coursePursueDao.selectCount(lambdaQueryWrapper);
                record.setIsPursue(count);
                LambdaQueryWrapper<CoursePursue> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CoursePursue::getCourseId,record.getCourseId());
                Integer integer = coursePursueDao.selectCount(queryWrapper);
                record.setPurseCount(integer);
                record.setListsDetail(courseDetails);
            }
            return Result.success().put("data",new PageUtils(courseIPage));
        }
        return Result.success().put("data",new PageUtils(null,0,0,0));
    }

    /**
     * 修改数据库视频谅解
     * @return
     */
    @Override
    public Result courseService() {
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.ge(CourseDetails::getCourseDetailsId,11);
        List<CourseDetails> courseDetails = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
        //https://url.7wcloud.com//jz/逆鳞/01.mp4
        if (ObjectUtils.isNotEmpty(courseDetails)){
            for (CourseDetails courseDetail : courseDetails) {
                if (ObjectUtils.isNotEmpty(courseDetail.getVideoUrl())){
                    String replace = courseDetail.getVideoUrl().replace("url", "u1").replace("jz", "7w");
                    courseDetail.setVideoUrl(replace);
                    courseDetailsDao.updateById(courseDetail);
                }
            }
        }
        return Result.success();
    }


}
